<?php
/**
 * Model class link to master_category in database
 *
 * @author Dat Nguyen <datnt@evolable.asia>
 */
class Category extends AppModel {
	var $name = 'Category';
	var $useTable = 'category';
	var $tablePrefix = 'master_';
	var $primaryKey = 'id';
	var $displayField = 'name';
	var $order = 'rank asc';

	/**
	 * Get category that belong to course
	 *
	 * @param $course
	 * @return mixed
	 */
	function getByCourse ($course) {
		$options = array(
			'conditions' => array(),
			'recursive' => -1,
		);
		if (isset($course['Course']['category'])) {
			$options['conditions'] = array(
				'id' => $course['Course']['category'],
			);
		}
		return $this->find('first', $options);
	}

	/**
	 * Get total courses in each category
	 *
	 * @return array
	 */
	function getCourseStatistic() {
		$options = array(
			'recursive' => -1,
			'fields' => array(
				$this->alias . '.*',
				'Course.total_course',
			),
			'joins' => array(
				array(
					'table' => '(SELECT c.category, COUNT(c.id) AS total_course FROM courses c WHERE c.del_flg = 0 GROUP BY c.category)',
					'alias' => 'Course',
					'type' => 'LEFT',
					'conditions' => array(
						$this->alias . '.id = Course.category',
					),
				),
			),
		);

		return $this->find('all', $options);
	}
}